const { isNumber } = require('lodash')
const { staff_collection } = require('../config')
const { grid_collection } = require('../config')
const { db } = require('../config')
const { command } = require('../config')
const _ = command
const department = require('../action/department');
const axios = require('axios'); // 在 Node.js 中引入 axios
// 计算装维分管区域中心点距离网格中心点距离
exports.main = async (event, context) => {
    // 1.获取所有网格的中心点经纬度保存到数组
    const gridInfo = await db.collection(grid_collection).field({ _id: false, center: true, grid: true }).get();
    var gridCenterArr = [];
    for (info of gridInfo.data) {
        gridCenterArr[info.grid] = info.center;
    }
    // return gridCenterArr;
    // 2.循环获取每个有中心点经纬度的装维的中心点经纬度
    const staffInfo = await db.collection(staff_collection).where({ status: _.neq('离职'), position: "全职装维" }).limit(1000).field({ name: true, center: true, grid: true }).get();
    // 3.发送请求到腾讯接口计算两点经纬度的距离
    var i = 0;
    for (staff of staffInfo.data) {
        staffGrid = staff.grid;
        staffCenter = staff.center;
        if (staffCenter) {
            fromLatLng = staffCenter.lat + ',' + staffCenter.lng;
            gridCenter = gridCenterArr[staffGrid];
            toLatLng = gridCenter.lat + ',' + gridCenter.lng;
            var url = 'https://apis.map.qq.com/ws/direction/v1/driving/?from=' + fromLatLng + '&to=' + toLatLng + '&output=jsonp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77';
            var failArr = [];
            // 使用示例
            var res = get(url)
                .then(data => {
                    data = JSON.parse(extractJsonContent(data))
                    if (data.result && typeof data.result === 'object') {
                        if ('routes' in data.result) {
                            var distance = parseFloat(((data.result.routes[0].distance) / 1000).toFixed(2));
                            db.collection(staff_collection).doc(staff._id).update({ centersDistance: distance }).then((res) => {
                                console.log(i++, staffInfo.data.length, staff._id, staff.name, distance, res, "请求返回成功");
                            });
                        } else {
                            failArr.push(staff.name)
                        }
                    } else {
                        console.log(data.result, url, 'data.result的值,url')
                    }
                })
                .catch(error => {
                    console.error(error, 'error')
                });
        }else{
            console.log(staff.name, 'staffCenter为空');
        }
        await delay(1000); // 每次循环等待 1 秒
    }
    return ['处理结束,失败名字和失败数：',failArr,failArr.length]
}
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
async function get(url) {
    try {
        const response = await axios.get(url);
        return response.data;
    } catch (error) {
        console.error('Error:', error);
    }
}
function isJsonObject(obj) {
    return typeof obj === 'object' && !Array.isArray(obj) && obj !== null;
}
function extractJsonContent(str) {
    // 使用正则表达式找到第一个 "{" 和最后一个 "}" 的位置
    const start = str.search(/\{/);
    const end = str.lastIndexOf('\}');

    // 检查是否找到了 "{"
    if (start === -1) {
        throw new Error('No opening "{" found.');
    }

    // 检查是否找到了 "}"
    if (end === -1) {
        throw new Error('No closing "}" found.');
    }

    // 使用 slice 方法从第一个 "{" 到最后一个 "}" 截取字符串
    const extractedContent = str.slice(start, end + 1);

    return extractedContent;
}
/** 依据 http状态码 判断请求是否成功 */
function isSuccessStatusCode(code) {
    return code >= 200 && code < 300;
}
